package com.docMan.utils;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Utilities;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;
/**
 * 
 * @author 小泽玛丽罗
 *
 */
public class Tif2Pdf {
	/**
	 * 将tif文件转换成pdf
	 * @param oldPath 要被转化的tif文件路径
	 * @param newPath 要生成的pdf文件的路径
	 * @return boolen
	 * @throws IOException 
	 */
	public static boolean convert(String oldPath, String newPath) throws IOException {
		// 创建一个文档对象
		Document doc = new Document();
		int pages = 0, comps = 0; 
		RandomAccessFileOrArray ra = null; 
		try {
	         try{ 
	           ra = new RandomAccessFileOrArray(oldPath); 
	           comps = TiffImage.getNumberOfPages(ra); 
	         } catch (Throwable e){ 
	           System.out.println("Exception in " + oldPath + " " + e.getMessage()); 
	         } 
			// 定义输出文件的位置
			PdfWriter.getInstance(doc, new FileOutputStream(newPath));
			// 开启文档
			doc.open();

				
				Object localObject1 = null;
				Object localObject2 = null;
				Image localImage1 = null;
				URL paramURL = Utilities.toURL(oldPath);
				try {
					if (paramURL.getProtocol().equals("file")) {
						localObject2 = paramURL.getFile();
						localObject2 = Utilities
								.unEscapeURL((String) localObject2);
						localObject1 = new RandomAccessFileOrArray(
								(String) localObject2);
					} else {
						localObject1 = new RandomAccessFileOrArray(paramURL);
					}

					int pageNums = TiffImage
							.getNumberOfPages((RandomAccessFileOrArray) ra);
					if (pageNums > 0) {
						for (int i = 1; i <= pageNums; i++) {
							localObject2 = TiffImage.getTiffImage(
									(RandomAccessFileOrArray) localObject1, i);
							Image jpg = (Image) localObject2;
							// 获得图片的高度
							float heigth = jpg.getHeight();
							float width = jpg.getWidth();
							// 合理压缩，h>w，按w压缩，否则按w压缩
							float percent = getPercent(heigth, width);

							// 设置图片居中显示
							jpg.setAlignment(Image.MIDDLE);
							// 按百分比显示图片的比例
							if(width>heigth){
								doc.setPageSize(PageSize.A3.rotate());
								doc.newPage();
								percent= (1191/width*100);
								jpg.scalePercent(percent);
								//System.out.println("缩小后的大小h:"+jpg.getScaledHeight()+"w:"+jpg.getScaledWidth());
								doc.setPageSize(PageSize.A3.rotate());
							}else {
								percent=(595/width*100);
								jpg.scalePercent(percent);
								doc.setPageSize(PageSize.A4);
							}
							doc.setMargins(0, 0, 0, 0);
							doc.add(jpg);
						}
					}
					if (localObject1 != null)
						((RandomAccessFileOrArray) localObject1).close();

				} finally {
					if (localObject1 != null)
						((RandomAccessFileOrArray) localObject1).close();
				}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (doc != null) {
				doc.close();
			}
			ra.close();
		}
		return true;
	}

	/**
	 * 第一种解决方案 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩
	 * 
	 * @param h
	 * @param w
	 * @return
	 */

	public static int getPercent(float h, float w) {
		int p = 0;
		float p2 = 0.0f;
		if (h > w) {
			p2 = 210 / h * 297;
		} else {
			p2 = 210 / w * 297;
		}
		p = Math.round(p2);
		return p;
	}

	/**
	 * 第二种解决方案，统一按照宽度压缩 这样来的效果是，所有图片的宽度是相等的
	 * 
	 * @param args
	 */
	public static int getPercent2(float h, float w) {
		int p = 0;
		float p2 = 0.0f;
		p2 = 530 / w * 100;
		p = Math.round(p2);
		return p;
	}
	static void convertTif(String filePath) throws IOException{
		File root=new File(filePath);
		File[] files=root.listFiles();
		for (File file : files) {
			if(file.isFile()){
				System.out.println(file.getAbsolutePath().replace(".tiff",".pdf"));
				if(!file.getAbsolutePath().endsWith(".pdf"))
					convert(file.getAbsolutePath(), file.getAbsolutePath().replace(".tiff",".pdf"));
			}else{
				convertTif(file.getAbsolutePath());
				System.out.println(file.getAbsolutePath());
			}
		}
	}
	
	
}
